﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Wise.Util.Queryable
{
    /// <summary>
    /// lambdaHelper lambda助手
    /// </summary>
    public class LambdaHelper:HelperBase<LambdaHelper>
    {
        /// <summary>
        /// 使用与关系合并两个表达式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Expression<Func<T, bool>> AndAlso<T>(
      Expression<Func<T, bool>> a,
      Expression<Func<T, bool>> b)
        {
            return instance.doAndAlso<T>(a, b);
           
        }

        /// <summary>
        /// 使用或关系 合并两个表达式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Expression<Func<T, bool>> OrElse<T>(
    Expression<Func<T, bool>> a,
    Expression<Func<T, bool>> b)
        {
            return instance.doOrElse<T>(a, b);
        }



        protected virtual Expression<Func<T, bool>> doAndAlso<T>(Expression<Func<T, bool>> a, Expression<Func<T, bool>> b)
        {
            var p = Expression.Parameter(typeof(T), "x");
            var bd = Expression.AndAlso(
                    Expression.Invoke(a, p),
                    Expression.Invoke(b, p));
            var ld = Expression.Lambda<Func<T, bool>>(bd, p);
            return ld;
        }

        protected virtual Expression<Func<T, bool>> doOrElse<T>(Expression<Func<T, bool>> a, Expression<Func<T, bool>> b)
        {
            var p = Expression.Parameter(typeof(T), "x");
            var bd = Expression.OrElse(
                    Expression.Invoke(a, p),
                    Expression.Invoke(b, p));
            var ld = Expression.Lambda<Func<T, bool>>(bd, p);
            return ld;
        }
           
    }
}
